package com.ecube.maintenance.components.activity;

import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.UserAction;
import com.ecube.maintenance.components.fragment.DealerListFragment;
import com.ecube.maintenance.components.fragment.NavigationDrawerFragment;
import com.ecube.maintenance.components.fragment.OrderedListFragment;
import com.ecube.maintenance.components.fragment.UserInfoFragment;
import com.ecube.maintenance.components.widget.ContactUsDialog;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.DeviceUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends CustomFragmentActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks, ActionBar.OnNavigationListener {
    long lastPressTime = 0;
    boolean updateManual = false;//是否是手动
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private CharSequence mTitle;
    //    private ActionBarState actionBarState;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UmengUpdateAgent.update(this);
        updateManual = false;
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();
        getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                if (getFragmentManager().getBackStackEntryCount() == 0) {
                    mDrawerToggle.setDrawerIndicatorEnabled(true);
                } else mDrawerToggle.setDrawerIndicatorEnabled(false);
            }
        });

        // Set up the drawer.
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                mDrawerLayout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                //revertActionBar();
                invalidateOptionsMenu(); // calls f()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                //configureActionBar();
                updateDrawer();
                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };
        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        restoreActionBar();
        initFeedback();
        getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                int i = getFragmentManager().getBackStackEntryCount();
//                Fragment f = getFragmentManager().f
            }
        });
    }

    void initFeedback() {
        FeedbackAgent agent = new FeedbackAgent(this);
        agent.sync();
        com.umeng.fb.model.UserInfo userInfo = agent.getUserInfo();
        if (userInfo == null) {
            userInfo = new com.umeng.fb.model.UserInfo();
        }
        Map<String, String> contact = userInfo.getContact();
        if (contact == null)
            contact = new HashMap<String, String>();
        UserInfo ui = UserInfo.getInstance();
        contact.put("user_device_key", DeviceUtil.getIMEI());
        contact.put("sid", ui.getSid());
        contact.put("mobile", ui.getMobile());
        userInfo.setContact(contact);
        agent.setUserInfo(userInfo);
    }

    private void updateDrawer() {
        if (mNavigationDrawerFragment != null) {
            mNavigationDrawerFragment.notifyDataChange();
        }
    }

    /**
     * 按照点击的position选择展示相应的fragment
     *
     * @param position
     */
    @Override
    public void onNavigationDrawerItemSelected(int position) {
        Fragment f;
        switch (position) {
            case 0://a list of dealer.
                cleanUpStack();
                f = DealerListFragment.newInstance();
                break;
            case 1://show the orders user have ordered.
                cleanUpStack();
                if (!UserInfo.isLogin()) {
                    Bog.toast(getString(R.string.ask_login));
                    return;
                }
                f = OrderedListFragment.newInstance();
                break;
            case 2://user info
                cleanUpStack();
                if (!UserInfo.isLogin()) {
                    Bog.toast(getString(R.string.ask_login));
                    return;
                }
                f = UserInfoFragment.newInstance();
                break;
            case 3://收藏
                Toast.makeText(getApplicationContext(), getString(R.string.coming_soon), Toast.LENGTH_SHORT).show();
                return;
            case 4://update to the latest version
                Bog.toast(R.string.message_check_update);
                updateManual = true;
                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
                    @Override
                    public void onUpdateReturned(int i, UpdateResponse updateResponse) {
                        if ( !updateManual )return;
                        if ( updateResponse == null ){
                            Bog.toast(R.string.message_check_update_error);
                        } else if (!updateResponse.hasUpdate) {
                            Bog.toast(R.string.message_up_to_date);
                        }
                    }
                });
                UmengUpdateAgent.update(this);
                return;
            case 5://user feed back
//                f = FeedBackFragment.newInstance();
                FeedbackAgent agent = new FeedbackAgent(this);
                agent.startFeedbackActivity();
                return;
            case 6://contact us
                ContactUsDialog dialog = new ContactUsDialog(this);
                dialog.show();
                return;
            case 7://logout
                logout();
                //clean up the stack before logout.
                getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                return;

            default:
                f = new Fragment();
                break;

        }

        FragmentTransaction ft = getFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        if (position == 0) {
            ft.replace(R.id.container, f).commit();
        } else ft.replace(R.id.container, f).addToBackStack(null).commit();
    }

    private void cleanUpStack() {
        getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    private void logout() {
        UserInfo ui = UserInfo.getInstance();
        UserAction.logouts(ui.getSid(), null);
        ui.setSid(null);
        UserInfo.saveToSpf(ui);
        Bog.toast("退出成功");

    }

    public void onSectionAttached(int number) {

    }

    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayHomeAsUpEnabled(true);
        /*Bitmap bitmap = getUserAvatarBmp();

        if(bitmap!=null){
            actionBar.setIcon(new BitmapDrawable(getResources(),bitmap));
        }*/
        TextView tv = (TextView) getLayoutInflater().inflate(R.layout.item_ab_spinner, null);
        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isDrawerOpen()) {
                    Bog.toast(getString(R.string.unavailable_city_selecting));
                    //TODO 城市选择
                    /*getFragmentManager().beginTransaction().replace(R.id.container,
                            CitySelectorFragment.newInstance())
                            .addToBackStack("CSF").commit();*/
                }
            }
        });
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(tv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            getMenuInflater().inflate(R.menu.main, menu);
            //restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    public boolean isDrawerOpen() {
        return mNavigationDrawerFragment.isDrawerOpen();
    }

    @Override
    public void onBackPressed() {
        int count = getFragmentManager().getBackStackEntryCount();
        long cur = System.currentTimeMillis();

        if (count == 0) {
            if (cur - lastPressTime > 1750) {
                lastPressTime = cur;
                Bog.toast("再按一次退出应用");
                return;
            } else {
                super.onBackPressed();
            }
        } else {
            getFragmentManager().popBackStack();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                if (getFragmentManager().getBackStackEntryCount() != 0) {
                    getFragmentManager().popBackStack();

                    return true;
                }
                break;
            case R.id.action_search:
                getActionBar().getCustomView().setVisibility(View.GONE);
                item.expandActionView();
                break;
        }
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        return false;
    }
}
